﻿//////////////////////////////////////////////////////////////////////////
//
//UBE Wars
//Owner = Barış Soner Uşaklı
//
//////////////////////////////////////////////////////////////////////////


using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using Tao.OpenGl;

namespace rkShared
{
    //Represents a 2d texture
	public class Texture
    {
        //OpenGL texture ID used to bind the texture
        private int textureID;
        
		public Texture(string filename):this(filename,false)
		{

		}

        public Texture(string filename,bool alpha)
        {
      
			Bitmap image = new Bitmap(filename);
			
			
			image.RotateFlip(RotateFlipType.RotateNoneFlipY);
			
			System.Drawing.Imaging.BitmapData bitmapdata;
			Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);

			if(alpha == false)
			bitmapdata = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
				System.Drawing.Imaging.PixelFormat.Format24bppRgb);
			else 
				bitmapdata = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
				System.Drawing.Imaging.PixelFormat.Format32bppArgb);


			Gl.glGenTextures(1, out textureID);
			Gl.glBindTexture(Gl.GL_TEXTURE_2D, textureID);

			//Build mipmaps
			if(alpha==false)
				Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D,(int)Gl.GL_RGB8,image.Width,image.Height,Gl.GL_BGR_EXT,Gl.GL_UNSIGNED_BYTE,bitmapdata.Scan0);
			else
				Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D,(int)Gl.GL_RGBA,image.Width,image.Height,Gl.GL_BGRA_EXT,Gl.GL_UNSIGNED_BYTE,bitmapdata.Scan0);

			
			Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR_MIPMAP_LINEAR);
			Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);		

			image.UnlockBits(bitmapdata);
			image.Dispose();
			
           
        }
					

		//bind this texture before drawing an object
		public void Bind()
		{
			Gl.glBindTexture(Gl.GL_TEXTURE_2D,textureID);
		}
		//Destroy the texture must be called explicitly
		public void Destroy()
		{
			Gl.glDeleteTextures(1,ref textureID);
		}
    }
}
